package thread.multi;

import java.util.concurrent.locks.ReentrantLock;

public class ThreadLock {
    public static void main(String[] args) {
        Lock lock = new Lock();
        new Thread(lock,"我").start();
        new Thread(lock,"黄牛").start();
        new Thread(lock,"蛇皮怪").start();
    }
}

class Lock implements Runnable {

    public int tickets = 10;

    //定义lock锁
    private final ReentrantLock lock= new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try {
                //加锁
                lock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName()+"得到票"+tickets--);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            } finally {
                //解锁
                lock.unlock();
            }

        }
    }
}
